# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import importlib
from redis import asyncio
from fastapi_cache.backends.redis import RedisBackend

__all__ = ["redis_be"]


def __loading_redis_configs():
    """ Load Redis configuration """
    configs = {}
    try:
        package = importlib.import_module("config")
        clz = getattr(package, "GlobalSetting", None)
        if not clz:
            return configs

        obj = clz().dict()
        redis_config = obj.get("REDIS", {})
        return redis_config
    except ModuleNotFoundError:
        return configs


def register_redis():
    """ Connect Redis """
    c = __loading_redis_configs()
    host: str = c.get("host", "127.0.0.1")
    port: int = int(c.get("port", 6379))

    return asyncio.from_url(
        f"redis://{host}:{port}",
        db=int(c.get("db", 0)),
        encoding=c.get("encoding", "utf-8"),
        username=c.get("username", ""),
        password=c.get("password", ""),
        max_connections=c.get("max_connections"),
        decode_responses=c.get("decode_responses", True)
    )


redis_be: RedisBackend = RedisBackend(register_redis())
